<!--
    @author Yancy Zhang
    @date 2022/4/7
    @description 编辑博客
-->
<template>
  <div class="edit-blog">
    <el-form ref="form" :model="blog" label-width="80px">
      <el-form-item label="文章标题">
        <el-input v-model="blog.blog_title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章封面">
        <el-input v-model="blog.blog_cover_img" placeholder="请输入文章的封面图片超链接"></el-input>
      </el-form-item>
      <el-form-item label="文章简述">
        <el-input type="textarea" v-model="blog.blog_desc" placeholder="请输入文章简述"></el-input>
      </el-form-item>
      <el-form-item label="文章分类">
        <el-select v-model="blog.blog_type" placeholder="请选择文章类型">
          <el-option label="前端开发" value="frontEnd"></el-option>
          <el-option label="Nodejs" value="node"></el-option>
          <el-option label="前端算法" value="arithmetic"></el-option>
          <el-option label="面试" value="interview"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <mavon-editor v-model="blog.blog_md_content" ref="md" @imgAdd="$imgAdd" @imgDel="$imgDel"/>
    <div class="btn">
      <el-button type="primary" @click="updateBlog">更新博客</el-button>
    </div>
  </div>
</template>

<script>
import {addImg, getBlogDetail, updateBlog} from "../../http/api";
export default {
  name: "AddBlog",
  data(){
    return{
      blog:{}
    }
  },
  created() {
    getBlogDetail(this.$route.params.id).then(res=>{
      this.blog = res;
    }).catch(error=>{
      this.$message.error(error);
    })
  },
  methods:{
    // 绑定@imgAdd event 上传图片到服务器
    $imgAdd(pos, $file){
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append('image', $file);
      addImg(formdata).then((res) => {
        /*将返回的文件路径返回给编辑器 显示在界面上*/
        this.blog.blog_img_list.push('/upload/'+res.data.filename);
        this.$refs.md.$img2Url(pos, '/upload/'+res.data.filename);
      })
    },
    /*删除已经上传了的图片*/
    $imgDel(){

    },
    /*更新博客*/
    updateBlog(){
      console.log(this.blog)
      updateBlog(this.blog).then(res=>{
        this.$message.success('更新成功！');
        this.$router.push('/admin');
      }).catch(res=>{
        this.$message.error(res);
      })
    }
  }
}
</script>

<style scoped>
.btn{
  padding: 20px 0;
  width: 100%;
  text-align: center;
}
.btn button{
  width: 200px;
}
</style>
